#include <stdio.h>

int binarySearch(int arr[], int length, int target) {
    int left  = 0;
    int right = length - 1;

    while (left <= right) {
        int mid = left + (right - left) / 2; // 避免整数溢出

        if (arr[mid] == target) {
            return mid;      // 找到目标，返回索引
        } else if (arr[mid] < target) {
            left = mid + 1;  // 目标在右半部分
        } else {
            right = mid - 1; // 目标在左半部分
        }
    }

    return -1; // 未找到目标
}

int findInsertPosition(int arr[], int length, int target) {
    int left = 0, right = length - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (arr[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return left; // 目标应插入的位置
}

int main() {
    int arr[]  = {2, 4, 6, 8, 10, 12, 14};
    int length = sizeof(arr) / sizeof(arr[0]);
    int target = 3;

    // int result = binarySearch(arr, length, target);
    int result = findInsertPosition(arr, length, target);

    if (result != -1) {
        printf("元素 %d 的索引是 %d\n", target, result); // 输出：元素 10 的索引是 4
    } else {
        printf("元素未找到\n");
    }

    return 0;
}